<?php

/*
	Class: Mail_IndexController

	About: Author
		Jaybill McCarthy

	About: License
		<http://communit.as/docs/license>
*/
class Mail_IndexController extends Cts_Controller_Action_Abstract {

	/* Group: Instance Methods */

	/*
		Function: init
	*/
	function init() {
		parent::init();
	}

	/* Group: Actions */

	/*
		Function: delete
	*/
	function deleteAction() {
		$mail_table = new MailMessages();
		if ($this->getRequest()->isPost()) {
			$confirm = $this->_request->getParam('delete', null);
			$id = $this->_id;
			$filter = new Zend_Filter_Alpha();
			$id = (int)$this->_request->getParam('id', 0);
			$del = $filter->filter($this->_request->getPost('delete'));
			if ($confirm == "Yes" and !is_null($id)) {
				$where = 'id = '.$id;
				$mail_table->delete($where);
			}
			$this->_redirect('/mail/index/index');
		} else {
			$id = (int)$this->_request->getParam('id', 0);
			if ($id > 0) {
				$message = $mail_table->fetchRow('id='.$id);
				if(($message->from_username == $this->_identity->username and $message->folder == "SENT")
				 OR ($message->to_username == $this->_identity->username and $message->folder == "INBOX")) {
					$this->view->message = $message->toArray();
				} else {
					die("Wow. Trying to delete other people's mail. Never thought of that one. Let me just write down your IP.");
				}
			}
		}
	}

	/*
		Function: view
	*/
	function viewAction() {
		$mail_table = new MailMessages();
		$id = $this->_request->getParam('id', null);
		$message = $mail_table->fetchRow('id='.$id);
		if (!is_null($message)) {
			if ($message->to_username != $this->_identity->username and $message->from_username != $this->_identity->username) {
				//This will only arise if someone appends a message id randomly or some other shady black sorcery.
				die("Trying to read other people's mail? Nice try. Let me just write down your IP there, Captain Caught.");	
			}
			$users_table = new Users();
			$from_where = $users_table->getAdapter()->quoteInto('username = ?', $message->from_username);
			$from_user = $users_table->fetchRow($from_where);
			$to_where = $users_table->getAdapter()->quoteInto('username = ?', $message->to_username);
			$to_user = $users_table->fetchRow($to_where)->toArray();
			if (!is_null($from_user)) {
				$this->view->from_user = $from_user->toArray();
			}
			$this->view->to_user = $to_user;
			$message->message = stripslashes($message->message);
			$this->view->message = $message->toArray();
			//if this message is to us (ie not a sent message) and 'new' then update the status to 'read'
			if ($message->status == "NEW" and $message->to_username == $this->_identity->username) {
				$data = array('status' => 'READ');
				$mail_table->update($data, 'id='.$message->id);				
			}			
			$this->view->pagetitle = "View Message";
		} else {
			// non existant message id. redirect.
			$this->view->errors = array("That message does not exist.");
		}
	}

	/*
		Function: index
	*/
	function indexAction() {
		$message = $this->_request->getParam('message', null);
		$this->view->success = $message;
		$mail_table = new MailMessages();
		$mail = array();
		$folder = $this->_request->getParam('folder', null);
		$whereclause = null;
		switch ($folder) {
			case "sent":
				$whereclause = $mail_table->getAdapter()->quoteInto('from_username= ? and folder = "SENT" ', $this->_identity->username);
				$this->view->pagetitle = "Sent Items";
				$_folder = "sent";
				break;			
			default:
				$_folder = "inbox";							
				$whereclause = $mail_table->getAdapter()->quoteInto('to_username= ? and folder = "INBOX" ', $this->_identity->username);				
				$new = $mail_table->getCountByWhereClause($whereclause.'and status="NEW"');
				$title = "Inbox";
				if ($new > 0) {
					$title .= " ($new)";
				}
				$this->view->pagetitle = $title;
				break;
		}
		$this->view->folder = $_folder;
		$per_page = Cts_Registry::get('messages_per_page', 'mail');
		$page = $this->_request->getParam('page', 0);
		$total = $mail_table->getCountByWhereClause($whereclause);
		$params = array('folder' => $_folder);
		$url = "/mail/index/index";
		$mail_rows = $mail_table->fetchAll($whereclause, 'sent_date desc', $per_page, $per_page * $page)->toArray();
		$this->makePager($page, $per_page, $total, $url, $params);
		$i = 0;
		foreach ($mail_rows as $mail_row) {
			$tmp_mail = $mail_row;
			$users_table = new Users();
			$where = $users_table->getAdapter()->quoteInto('username = ?', $tmp_mail['from_username']);
			$from_user = $users_table->fetchRow($where);
			if (is_null($from_user)) {
				$tmp_mail['user_missing'] = true;
			}
			$tmp_mail['cssclass'] = "mail-status-".strtolower($tmp_mail['status']);
			$tmp_mail['statusword'] = ucfirst(strtolower($tmp_mail['status']));
			
			$tmp_mail['subject'] = stripslashes($tmp_mail['subject']);
			
			$mail[] = $tmp_mail;
		}
		$this->view->mail = $mail;
	}

	/*
		Function: new
	*/
	function newAction() {
		$mail_table = new MailMessages();
		$users_table = new Users();
		$request = new Cts_Request($this->getRequest());
		if ($this->_auth->hasIdentity()) {
			$from_username = $this->_identity->username;
		}
		if ($request->has('replytoid')) {
			$replytoid = $request->replytoid;
		} else {
			$replytoid = null;
		}			
		if ($this->getRequest()->isPost()) { // we are posting		
			if ($request->has('striptags')) {
				$striptags = (boolean)$request->striptags;
			} else {
				$striptags = false;
			}
			$strip_array = array('subject');
			if ($striptags and $request->has('body')) {
				$strip_array[] = "body";
			}
			$request->stripTags($strip_array);			
			$errors = array();
			if ($request->has('subject')) {
				$subject = $request->subject;
			} else {
				$subject = null;
			}
			if ($request->has('body')) {
				$body = $request->body;
			} else {
				$body = null;
			}
			if ($request->has('to_username')) {
				$to_username = $request->to_username;
			} else {
				$to_username = null;
			}
			$where = $users_table->getAdapter()->quoteInto('username = ?', $to_username);
			$to_user = $users_table->fetchRow($where);
			if (!is_null($replytoid)) {
				$reply_to_message = $mail_table->fetchRow('id='.$replytoid)->toArray();
				if (count($reply_to_message) > 0) {
					$subject = $reply_to_message['subject'];
					if (substr($subject,0,4) != "RE: ") {
						$subject = "RE: " . $reply_to_message['subject'];
					}
					$replytoid = $reply_to_message['id'];
				} else {
					$replytoid = null;
				}
			}
			$body_validator = new Zend_Validate();
			$body_validator->addValidator(new Zend_Validate_StringLength(1, 50000));
			$subject_validator = new Zend_Validate();
			$subject_validator->addValidator(new Zend_Validate_StringLength(1, 100));
			if (!$subject_validator->isValid($subject)) {
				foreach ($subject_validator->getMessages() as $message) {
					$errors[] = "Subject: " . $message;
				}	
			}
			if (!$body_validator->isValid($body)){
				foreach ($body_validator->getMessages() as $message) {
					$errors[] = "Message: " . $message;
				}	
			}
			if (count($errors) != 0) {
				$this->view->errors = $errors;
				$this->view->subject = $subject;
				$this->view->body = $body;
			} else {
				$mail_table = new MailMessages();
				$data = array(
					'from_username' => $from_username,
					'subject' => $subject,
					'message' => $body,
					'status' => 'NEW',
					'sent_date' => date(DB_DATETIME_FORMAT, time()),
				);
				// prepare notification email
				$subject = $this->_T("New message from")." ".$this->_identity->username;
				$email_params = array(
					"url" => Cts_Registry::get('site_url')."/mail/index",
					"from"	=> Cts_Registry::get('site_from'),				
				);				
				$email = new Cts_Email(null,"mail");				
				$data['to_username'] = $to_username;
				$mail_table->insert($data);
				$email->sendEmail($subject,$to_user->email,"newmessage.tpl",$email_params);
				// copy to sent items
				$data['folder'] = 'SENT';
				$data['status'] = 'SENT';
				$mail_table->insert($data);
				//Update status of replied to message
				if (!is_null($replytoid)) {
					$data = array('status' => 'REPLIED');
					$mail_table->update($data,'id='.$replytoid);
				}
				//redirect
				if ($this->_auth->hasIdentity()) {
					$this->_redirect('/mail/index/index/index/message/'.urlencode("Message Sent."));
				} else {
					$this->_redirect('/');
				}
			}
		}
		if ($this->_auth->hasIdentity()) {
			$to_username = $this->_request->getParam('to',null);
		} else {
			$this->_redirect('/auth/missing');
		}
		if (!is_null($replytoid)) {
			$reply_to_message = $mail_table->fetchRow('id='.$replytoid)->toArray();
			if (!is_null($reply_to_message)) {
				$subject = $reply_to_message['subject'];
				if (substr($reply_to_message['subject'], 0, 4) != "RE: ") {
					$subject = "RE: " . $reply_to_message['subject'];
				}
				$this->view->subject = $subject;
				$from_where = $users_table->getAdapter()->quoteInto('username = ?', $reply_to_message['from_username']);
				$from_user = $users_table->fetchRow($from_where)->toArray();
				$this->view->from_user = $from_user;
				$this->view->reply_to_message = $reply_to_message;
				$this->view->replytoid = $replytoid;
			}
		}
		if (!is_null($to_username)) {
			$where = $users_table->getAdapter()->quoteInto('username = ?',$to_username);			
			$to_user = $users_table->fetchRow($where);
		}
		if (is_null($to_user)) {
			$this->errors = array($this->_t('The user you are trying to contact does not exist.'));
		} else {
			$this->view->to_user = $to_user->toArray();
			$this->view->loadEditor = true;
		}
	}

}
